<template>
  <div style="height: 100%">
    <div class="login-container login_main">
      <!-- 顶部logo -->
      <div class="header">
        <div class="logo">
          <img :src="brandInfo.homeLogo" alt style="width:117px" />
          <div style="margin-left:10px">合作伙伴平台</div>
        </div>
      </div>

      <!-- 登录 -->
      <div class="login_center">
        <div class="login_img">
          <div style="width:440px;height:480px"><img src="@/assets/images/logo1.gif" alt="" style="width:100%;height:100%"></div>
        </div>
        <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" autocomplete="on" label-position="left">
          <div class="title-container">
            <div class="title_img">登录</div>
          </div>
          <el-form-item prop="username">
            <span class="svg-container">
              <svg-icon icon-class="user" />
            </span>
            <el-input ref="username" v-model="loginForm.username" placeholder="账号" name="username" type="text" tabindex="1" autocomplete="on" />
          </el-form-item>
          <el-tooltip v-model="capsTooltip" content="Caps lock is On" placement="right" manual>
            <el-form-item prop="password" class="login_password">
              <span class="svg-container">
                <svg-icon icon-class="password" />
              </span>
              <el-input ref="password" v-model="loginForm.password" :key="passwordType" :type="passwordType" placeholder="密码" name="password" tabindex="2" autocomplete="on" @keyup.native="checkCapslock"
                @blur="capsTooltip = false" @keyup.enter.native="handleLogin" />
              <span class="show-pwd" @click="showPwd">
                <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
              </span>
            </el-form-item>
          </el-tooltip>
          <el-button :loading="loading" type="primary" style="width:100%;margin-bottom:30px;" @click.native.prevent="handleLogin" class="login_bottom">登录</el-button>
          <div class="flex flex_bet enroll">
            <div>
              <a href="javascript:void(0);" @click="enrolldialogVisible = true">立即注册</a>
            </div>
            <div>
              <a href="javascript:void(0);" @click="changedialogVisible = true">忘记密码</a>
            </div>
          </div>
        </el-form>
      </div>
      <div class="login_ys">
        <p @click="gotoBh" style="cursor: pointer;">{{brandInfo.icp}}</p>
        <p>{{brandInfo.companyName}}</p>
      </div>
    </div>
    <!-- 隐藏的注册对话框 -->
    <el-dialog title="注册教管壹账号" :visible.sync="enrolldialogVisible" width="30%" center @close="addFormclose" :close-on-click-modal="false" :close-on-press-escape="false">
      <div class="register ">
        <el-form :model="enrollForm" :rules="enrollrules" ref="ruleForm" style="width:70%">
          <el-form-item prop="username">
            <el-input v-model="enrollForm.username" autocomplete="on" placeholder="请输入您的账号名称"></el-input>
          </el-form-item>
          <el-form-item prop="realname">
            <el-input v-model="enrollForm.realname" autocomplete="on" placeholder="请输入您的昵称"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input ref="enrollPassword" v-model="enrollForm.password" autocomplete="on" placeholder="请输入您的密码" :key="enrollType" :type="enrollType"></el-input>
            <span class="show-pwd" @click="enrollshowPwd">
              <svg-icon :icon-class="enrollType === 'password' ? 'eye' : 'eye-open'" />
            </span>
          </el-form-item>
          <el-form-item prop="password2">
            <el-input v-model="enrollForm.password2" autocomplete="on" placeholder="请确认您的密码" :key="enrollTypes" :type="enrollTypes"></el-input>
            <span class="show-pwd" @click="enrollshowPwds">
              <svg-icon :icon-class="enrollTypes === 'password' ? 'eye' : 'eye-open'" />
            </span>
          </el-form-item>
          <el-form-item prop="mobile">
            <el-input v-model="enrollForm.mobile" autocomplete="on" placeholder="请输入您的手机号码"></el-input>
          </el-form-item>
          <el-form-item prop="phone">
            <el-input v-model="enrollForm.phone" autocomplete="on" placeholder="请输入推荐人的手机号码"></el-input>
          </el-form-item>
          <el-form-item prop="policy" class="policy flex felx_align flex_cen">
            <div class="flex felx_align">
              <el-checkbox v-model="enrollForm.policy">同意</el-checkbox>
              <router-link tag="a" target="_blank" :to="{path:'/treatys'}" style="color:#409EFF">《教管壹信息服务条款,隐私政策》</router-link>
            </div>
          </el-form-item>
          <div style="text-align:center">
            <Debounce>
              <el-button type="primary" style="width:40%" @click.native="enrollsubmitForm('ruleForm')" round>立即注册</el-button>
            </Debounce>
          </div>
        </el-form>
      </div>
    </el-dialog>
    <!-- 修改密码弹出框 -->
    <el-dialog title="忘记密码" :visible.sync="changedialogVisible" width="30%" center @close="changeFormclose" :close-on-click-modal="false" :close-on-press-escape="false">
      <div class="changedialog ">
        <el-form :model="changeForm" :rules="changerules" ref="changerules" style="width:75%">
          <el-form-item prop="mobile">
            <el-input v-model="changeForm.mobile" autocomplete="off" placeholder="请输入您的手机号码"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input ref="changePassword" v-model="changeForm.password" autocomplete="off" placeholder="请输入您的新密码" :key="changeType" :type="changeType"></el-input>
            <span class="show-pwd" @click="changeshowPwd">
              <svg-icon :icon-class="changeType === 'password' ? 'eye' : 'eye-open'" />
            </span>
          </el-form-item>
          <el-form-item prop="password2">
            <el-input v-model="changeForm.password2" autocomplete="off" placeholder="请确认您的新密码" :key="changeTypes" :type="changeTypes"></el-input>
            <span class="show-pwd" @click="changeshowPwds">
              <svg-icon :icon-class="changeTypes === 'password' ? 'eye' : 'eye-open'" />
            </span>
          </el-form-item>
          <el-form-item prop="code">
            <div class="addPut">
              <el-input v-model="changeForm.code" placeholder="请输入验证码"></el-input>
              <el-button class="dleValidation" size="mini" round @click="sendcode" :disabled="!codeShow">{{codeShow ? '获取验证码' : count + 's'}}</el-button>
            </div>
          </el-form-item>
          <div>
            <Debounce>
              <el-button type="primary" style="width:40%" @click.native="getupdatePassword('changerules')" round>确定</el-button>
            </Debounce>
          </div>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { registerSms, loginLaterNotice } from "@/api/infos.js";
import { userRegister, updatePassword } from "@/api/user.js";
import {mapGetters} from "vuex";

export default {
  name: "Login",
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        if (this.enrollForm.password2 !== '') {
          this.$refs.ruleForm.validateField('checkPass');
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.enrollForm.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    var validatePassTwo = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        if (this.changeForm.password2 !== '') {
          this.$refs.changerules.validateField('checkPass');
        }
        callback();
      }
    };
    var validatePass2Two = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.changeForm.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    var phoneReg = 11 && /^((13|14|15|17|18)[0-9]{1}\d{8})$/
    var validatePhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('号码不能为空!'))
      }
      if (!phoneReg.test(value)) {
        callback(new Error('手机号码有误'))
      } else {
        callback()
      }
    };
    var demand = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请先同意'))
      } else {
        callback()
      }
    };
    var ddddd = (value) => {
      let cnReg = /([\u4e00-\u9fa5]|[\u3000-\u303F]|[\uFF00-\uFF60])/g
      let mat = value.match(cnReg)
      let length
      if (mat) {
        length = (mat.length + (value.length - mat.length) * 0.5)
        return length
      } else {
        return value.length * 0.5
      }
    }
    var validateUsername = (rule, value, callback) => {
      let leng = ddddd(value)
      if (leng < 2) {
        return callback(new Error('中文最少两位字符，英文最少4位字符'))
      } else {
        callback()
      }
    }
    return {
      loginForm: { username: "", password: "" },
      loginRules: { username: [{ required: true, trigger: "blur", message: "请输入您的账号" }], password: [{ required: true, trigger: "blur", message: "请输入您的密码" }] },
      passwordType: "password",
      enrollType: "password",
      enrollTypes: "password",
      changeType: "password",
      changeTypes: "password",
      capsTooltip: false,
      loading: false,
      showDialog: false,
      redirect: undefined,
      otherQuery: {},
      //国际化切换
      langs_cut: { img: "", text: "" },
      enrolldialogVisible: false,
      //创建账号表单
      enrollForm: { username: "", password: "", password2: "", mobile: "", policy: '', last_ip: '', phone: '', realname: '' },
      //创建账号校验
      enrollrules: {
        username: [{ validator: validateUsername, trigger: 'blur' }],
        realname: [{ validator: validateUsername, trigger: 'blur' }],
        password: [{ validator: validatePass, trigger: 'blur' }, { min: 6, message: '密码不能小于6位', trigger: 'blur' }],
        password2: [{ validator: validatePass2, trigger: 'blur' }],
        mobile: [{ required: true, validator: validatePhone, trigger: 'blur' }],
        policy: [{ validator: demand, trigger: 'blur' }]
      },
      changedialogVisible: false,
      //修改密码
      changeForm: { last_ip: sessionStorage.getItem("Ip"), mobile: '', code: '', password: '', password2: '' },
      //修改密码校验
      changerules: {
        code: [{ required: true, trigger: "blur", message: "请输入验证码" }],
        password: [{ validator: validatePassTwo, trigger: 'blur' }, { min: 6, message: '密码不能小于6位', trigger: 'blur' }],
        password2: [{ validator: validatePass2Two, trigger: 'blur' }],
        mobile: [{ required: true, validator: validatePhone, trigger: 'blur' }]
      },
      codeShow: true,//验证码按钮
      count: '',//验证码倒计时
      timer: null,
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true
    }
  },
  methods: {
    //修改密码
    getupdatePassword(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let changeForm = JSON.parse(JSON.stringify(this.changeForm))
          updatePassword(changeForm).then(res => {
            this.$message.success(res.msg)
            this.changedialogVisible = false
          }).catch(err => { })
        } else {
          return false
        }
      })
    },
    //获取验证码
    sendcode() {
      let reg = 11 && /^((13|14|15|17|18)[0-9]{1}\d{8})$/;
      if (this.changeForm.mobile == '') return this.$message.error('请先输入手机号码')
      if (!reg.test(this.changeForm.mobile)) return this.$message.error('请输入正确的手机号码')
      this.verification()
    },
    //发送验证码
    verification() {
      registerSms({ phone: this.changeForm.mobile }).then(res => {
        this.$message.success(res.msg)
      }).catch(err => {
        //this.$message.error(err.msg)
      })
      const TIME = 60
      if (!this.count) {
        this.count = TIME
        this.codeShow = false
      }
      this.timer = setInterval(() => {
        if (this.count > 0 && this.count <= TIME) {
          this.count = this.count - 1
        } else {
          this.codeShow = true
          clearInterval(this.timer)
          this.timer = null
        }
      }, 1000);
    },
    checkCapslock(e) {
      const { key } = e;
      this.capsTooltip = key && key.length === 1 && key >= "A" && key <= "Z";
    },
    showPwd(type) {
      if (this.passwordType === "password") {
        this.passwordType = "";
      } else {
        this.passwordType = "password";
      }
      this.$nextTick(() => {
        this.$refs.password.focus();
      });
    },
    changeshowPwd(type) {
      if (this.changeType === "password") {
        this.changeType = "";
      } else {
        this.changeType = "password";
      }
      this.$nextTick(() => {
        this.$refs.changePassword.focus();
      })
    },
    changeshowPwds(type) {
      if (this.changeTypes === "password") {
        this.changeTypes = "";
      } else {
        this.changeTypes = "password";
      }
      this.$nextTick(() => {
        this.$refs.changePassword.focus();
      })
    },
    enrollshowPwd(type) {
      if (this.enrollType === "password") {
        this.enrollType = "";
      } else {
        this.enrollType = "password";
      }
      this.$nextTick(() => {
        this.$refs.enrollPassword.focus();
      })
    },
    enrollshowPwds(type) {
      if (this.enrollTypes === "password") {
        this.enrollTypes = "";
      } else {
        this.enrollTypes = "password";
      }
      this.$nextTick(() => {
        this.$refs.enrollPassword.focus();
      })
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true;
          this.$store.dispatch("user/login", this.loginForm).then(async () => {
            await loginLaterNotice({ userId: localStorage.getItem("ID") }).then(res => {//查看是否有更新提示
              this.$store.commit('user/LOGIN_LATER', res.data)
              //this.$router.push({ path: this.redirect || "/" })
              this.$router.push({ path: '/dashboard' || "/" })//默认跳转首页
              this.loading = false
            }).catch(err => {
              //this.$router.push({ path: this.redirect || "/" })
              this.$router.push({ path: '/dashboard' || "/" })
              this.loading = false
              this.$store.commit('user/LOGIN_LATER', '')

            })
          }).catch((err) => {
            this.$message.error(err.msg)
            this.loading = false
          })
        } else {
          return false;
        }
      });
    },
    //注册用户
    enrollsubmitForm(formName) {
      if (!this.enrollForm.policy) return this.$message.error('请先勾选协议')
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let enrollForm = JSON.parse(JSON.stringify(this.enrollForm))
          enrollForm.last_ip = sessionStorage.getItem("Ip")
          delete enrollForm.policy
          userRegister(enrollForm).then(res => {
            this.$message.success('您的注册资料已经提交，请耐心等待管理员审核')
            this.enrolldialogVisible = false
          }).catch(err => {
            this.$message.error(res.msg)
          })
        } else {
          return false;
        }
      })
    },
    addFormclose() {
      this.$nextTick(() => {
        this.enrollForm = { username: "", password: "", password2: "", mobile: "", policy: '', last_ip: '', phone: '', realname: '' }
      })
    },
    changeFormclose() {
      this.$nextTick(() => {
        this.$refs.changerules.resetFields();
        this.changeType = "password"
      })
    },
    gotoBh() {
      window.open('https://beian.miit.gov.cn', '_blank');
    }
  },
  computed: {
    ...mapGetters(['brandInfo'])
  }
};
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg: #283443;
$light_gray: #fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }
}
</style>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;

.dialog-pwd {
  position: absolute;
  right: 40px;
}

.login_main {
  position: relative;
}
.login_ys {
  position: absolute;
  bottom: 0;
  width: 100%;
  color: #fff;
  text-align: center;
  font-size: 12px;
}
.register {
  position: relative;
  left: 50%;
  transform: translateX(-35%);

  .el-input {
    display: inline-block;
    // width: 85%;
  }
  .show-pwd {
    position: absolute;
    right: 15px;
    top: 2px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
}
.changedialog {
  position: relative;
  left: 50%;
  transform: translateX(-35%);
  text-align: center;
  .show-pwd {
    position: absolute;
    right: 10px;
    top: 2px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
}
.enroll {
  color: #409eff;
  font-size: 14px;
}

.policy {
  margin-top: 10px;
}

.el-form-item {
  margin-top: 20px;
}
.login_password {
  margin-top: 40px;
}

.login-container {
  min-height: 100%;
  width: 100%;
  background-color: #242c3a;
  overflow: hidden;

  .login-form {
    position: relative;
    width: 420px;
    max-width: 100%;
    // padding: 160px 35px 0;
    // margin: 0 auto;
    overflow: hidden;
    background-color: #323a4a;
    border-radius: 10px;
    padding: 40px;
    z-index: 999;
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;
    display: flex;
    justify-content: center;
    padding: 20px 0;
    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
    .title_img {
      color: #dbe1e7;
      font-size: 25px;
      font-weight: 400;
      img {
        height: 100%;
        width: 100%;
      }
    }
    .set-language {
      position: absolute;
      right: 0;
      color: #fff;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }

  .thirdparty-button {
    position: absolute;
    right: 0;
    bottom: 6px;
  }

  @media only screen and (max-width: 470px) {
    .thirdparty-button {
      display: none;
    }
  }
}

.header {
  display: flex;
  padding: 10px 30px;
  width: 100%;
  z-index: 2;
  justify-content: space-between;
  align-items: center;
  .logo {
    display: flex;
    color: #fff;
    height: 40px;
    line-height: 40px;
  }
  .languge {
    display: flex;
    align-items: center;
    .languge_text {
      color: #dbe1e7;
      padding: 0 10px;
    }
    .languge_img {
      height: 30px;
      width: 30px;
      img {
        height: 100%;
        width: 100%;
      }
    }
    .set-language {
      color: #fff !important;
      height: 20px;
      width: 20px;
      font-size: 18px;
    }
  }
}
.login_center {
  display: flex;
  justify-content: center;
  padding: 160px 35px 0;
  .login_img {
    margin-right: 200px;
  }
  .login_bottom {
    height: 50px;
    margin-top: 20px;
  }
}
@media all and (max-width: 1150px) {
  .login_center {
    .login_img {
      display: none;
    }
  }
}
</style>
